//
//  ViewController.swift
//  MetaTest
//
//  Created by yhb on 2024/10/25.
//

import IQKeyboardManagerSwift
import ObjectMapper
import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var clearBn: UIBarButtonItem!
    @IBOutlet var sendBn: UIButton!
    @IBAction func sendMessageAction(_ sender: Any) {
        questionTextView.resignFirstResponder()
        self.sendMsg = questionTextView.text ?? ""
        if (questionTextView.text ?? "").isEmpty {
            ProgressHUD.failed("发送内容不能为空")
            return
        }
        let newQuestion = questionTextView.text ?? ""
        questionTextView.text = ""
        // 加载现有问题列表，并添加新的问题
        UserManager.shared.loadFromUserDefaults()
        UserManager.shared.questionList.append(newQuestion)
            
        // 保存问题列表
        UserManager.shared.saveQuestions(questionList: UserManager.shared.questionList)
            
        tableView.reloadData()
        ProgressHUD.animate("发送中...")
        clearBn.isEnabled = false
        sendBn.isEnabled = false
        sendBn.isUserInteractionEnabled = false
        // 使用 GCD 在后台队列中异步执行数据请求
        let queue = DispatchQueue.global(qos: .userInitiated)
        queue.async {
            // 在后台队列中执行网络请求
            self.getDataList { result in
                // 请求完成后回到主线程更新 UI
                DispatchQueue.main.async {
                    ProgressHUD.dismiss()
                    
                    self.tableView.reloadData()
                    self.clearBn.isEnabled = true
                    self.sendBn.isEnabled = true
                    self.sendBn.isUserInteractionEnabled = true
                    switch result {
                    case .success:
                        print("😄")
                    case .failure(let error):
                        ProgressHUD.failed(error.localizedDescription)
                    }
                }
            }
        }
    }

    @IBAction func clearBn(_ sender: Any) {
        UserManager.shared.answerList.removeAll()
        UserManager.shared.questionList.removeAll()
        UserManager.shared.removeAnswers()
        UserManager.shared.removeQuestions()
        tableView.reloadData()
    }
    @IBOutlet var sendQuestionBgView: UIView!
    
    @IBOutlet var questionTextView: IQTextView!
    @IBOutlet var tableView: UITableView!
    
    var sendMsg: String?
    
    let UserMsgCellId = "MsgTableViewCell"
    let AnswerMsgCellId = "AnswerTableViewCell"
    
    var url: String = "https://ark.cn-beijing.volces.com/api/v3/chat/completions"
    var modelCode: String = "ep-20241024192635-4kpxz"
    var previousContentOffset: CGPoint?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Meta测试"
        tableView.register(UINib(nibName: UserMsgCellId, bundle: nil), forCellReuseIdentifier: UserMsgCellId)
        tableView.register(UINib(nibName: AnswerMsgCellId, bundle: nil), forCellReuseIdentifier: AnswerMsgCellId)
        tableView.estimatedRowHeight = 50 // 设置一个估计高度
        tableView.rowHeight = UITableView.automaticDimension // 使用自动高度
        questionTextView.delegate = self
        tableView.delegate = self
        tableView.dataSource = self
        print("出现\(UserManager.shared.getQuestions())")
        print("出现\(UserManager.shared.answerList)")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        view.endEditing(true)
    }
    
    func getDataList(completion: @escaping (Result<Void, Error>) -> Void) {
        let params: [String: Any] = [
            "model": modelCode,
            "messages": [
                ["role": "user", "content": sendMsg ?? ""]
            ]
        ]
        
        MetaHttp.post(url: url, params: ["bodyList": params]) { result in
            let data = Mapper<MsgModel>().map(JSONObject: result)
            if data?.choices?.first?.finishReason == "stop", let answerData = data?.choices?.first?.message?.content {
                // 加载现有答案列表，并添加新的答案
                UserManager.shared.loadFromUserDefaults()
                UserManager.shared.answerList.append(answerData)
                            
                // 保存答案列表
                UserManager.shared.saveAnswers(answers: UserManager.shared.answerList)
            }
            completion(.success(()))
        } failure: { error in
            completion(.failure(error as! Error))
        }
    }
}

extension ViewController: UITextViewDelegate {
    func textViewDidBeginEditing(_ textView: UITextView) {
        // 文本框开始编辑时的处理
 
    }

    func textViewDidEndEditing(_ textView: UITextView) {
        // 文本框结束编辑时的处理
    }
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return UserManager.shared.questionList.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row % 2 == 0 { // 用户提问的 cell
            let userCell = tableView.dequeueReusableCell(withIdentifier: UserMsgCellId, for: indexPath) as! MsgTableViewCell
            userCell.questionLabel.text = UserManager.shared.questionList[indexPath.section]
            return userCell
        } else { // 回答的 cell
//            let answerCell = tableView.dequeueReusableCell(withIdentifier: AnswerMsgCellId, for: indexPath) as! AnswerTableViewCell
//
//            if indexPath.section == UserManager.shared.questionList.count - 1 { // 最后一个 cell
//                // 如果 answerList 的数量少于 questionList 的数量，显示加载动画
//                if UserManager.shared.answerList.count < UserManager.shared.questionList.count {
//                    answerCell.loadingView.isHidden = false
//                    answerCell.loadingView.startAnimating()
//                    answerCell.answerLabel.isHidden = true
//                } else {
//                    answerCell.loadingView.stopAnimating()
//                    answerCell.loadingView.isHidden = true
//                    answerCell.answerLabel.isHidden = false
//                    answerCell.answerLabel.text = UserManager.shared.answerList[indexPath.section]
//                }
//            } else {
//                // 对于其他 cell，显示已有的答案
//                answerCell.loadingView.stopAnimating()
//                answerCell.loadingView.isHidden = true
//                answerCell.answerLabel.isHidden = false
//                answerCell.answerLabel.text = UserManager.shared.answerList[indexPath.section]
//            }
            let answerCell = tableView.dequeueReusableCell(withIdentifier: AnswerMsgCellId, for: indexPath) as! AnswerTableViewCell
                    
            let isLastSection = indexPath.section == UserManager.shared.questionList.count - 1
            let answer = UserManager.shared.answerList.safeElement(at: indexPath.section)
                    
            answerCell.configure(with: answer, isLastSection: isLastSection)
            return answerCell
        }
    }
}

extension Array where Element == String {
    func safeElement(at index: Int) -> String? {
        return indices.contains(index) ? self[index] : nil
    }
}
